package sk.tramtatiri.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.FoodDao;
import sk.tramtatiri.data.dataobjects.Food;

public class FoodDaoJPAImp extends AbstractDaoJPAImpl<Food> implements FoodDao {

	public FoodDaoJPAImp() {
		super(Food.class);
	}

	@Transactional
	public List<Food> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<Food>>() {
			public List<Food> doInJpa(EntityManager em)
					throws PersistenceException {
				TypedQuery<Food> query = em.createQuery("select f from Food f order by f.name asc",
						Food.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public Food findName(final String name) {
		try{
			return getJpaTemplate().execute(new JpaCallback<Food>() {
				public Food doInJpa(EntityManager em) throws PersistenceException {
					TypedQuery<Food> query = em.createQuery("select f from Food f where name='"+name+"'", Food.class);
					return query.getSingleResult();
				}
		});
		}catch (Exception e) {
			return null;
		}
	}

	@Transactional
	public int countAll() {
		return getJpaTemplate().execute(new JpaCallback<Integer>() {

			public Integer doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Long> query = em.createQuery("select count (f) from Food f", Long.class);
				return (query.getSingleResult()).intValue();
			}
		});
	}
	
	@Transactional
	public List<String> findAllNames() {
		return getJpaTemplate().execute(new JpaCallback<List<String>>() {
			public List<String> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<String> query = em.createQuery("select f.name from Food f", String.class);
				return query.getResultList();
			}
		});
	}
	
	@Transactional
	public List<Food> orderBy(final String column) {
		return getJpaTemplate().execute(new JpaCallback<List<Food>>() {
			public List<Food> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Food> query = em.createQuery("select f from Food f order by " + column, Food.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public void delete(Food o) {
		Food f = getJpaTemplate().find(Food.class, o.getId());
		getJpaTemplate().remove(f);
	}
	
}
